import { requestWithErrorHandling } from "./request";

// 获取用户列表，支持传递查询参数（如分页）
export function fetchUsers(params = {}) {
  return requestWithErrorHandling({
    url: "/users",
    method: "get",
    params,
    errorMessage: "获取用户列表失败",
  }).then((res) => {
    if (res.code === 1 && res.data && Array.isArray(res.data.list)) {
      return {
        list: res.data.list.map((item) => ({
          ...item,
          // loginStatus 和 onlineDeviceCount 直接从返回数据获取
        })),
        total:
          typeof res.data.total === "number"
            ? res.data.total
            : res.data.list.length,
      };
    }
    return { list: [], total: 0 };
  });
}

// 用户登录
export function login(data) {
  return requestWithErrorHandling({
    url: "/users/login",
    method: "post",
    data,
    errorMessage: "登录失败",
  });
}

// 用户注册
export function register(data) {
  return requestWithErrorHandling({
    url: "/users/register",
    method: "POST",
    data: {
      password: data.password,
      name: data.name,
      age: data.age,
      email: data.email,
      img: data.img,
      verificationCode: data.verificationCode,
    },
    errorMessage: "注册失败",
  });
}

// 用户登出
export function logout(userId) {
  return requestWithErrorHandling({
    url: `/users/logout/${userId}`,
    method: "post",
    errorMessage: "登出失败",
  });
}

// 创建用户
export function createUser(data) {
  return requestWithErrorHandling({
    url: "/users",
    method: "POST",
    data: {
      password: data.password,
      name: data.name,
      age: data.age,
      email: data.email,
      // 头像字段
      ...(data.img ? { img: data.img } : {}),
    },
    errorMessage: "创建用户失败",
  });
}

// 修改用户
export function updateUser(data) {
  const requestData = {
    id: data.id,
    name: data.name,
    age: data.age,
    email: data.email,
    role: data.role,
    // 头像字段
    ...(data.img ? { img: data.img } : {}),
  };

  // 只有当密码存在时才包含密码字段
  if (data.password && data.password.trim()) {
    requestData.password = data.password;
  }

  return requestWithErrorHandling({
    url: "/users",
    method: "PUT",
    data: requestData,
    errorMessage: "更新用户失败",
  });
}

// 删除单个用户
export function deleteUser(id) {
  return requestWithErrorHandling({
    url: `/users/${id}`,
    method: "DELETE",
    errorMessage: "删除用户失败",
  });
}

// 批量删除用户
export function batchDeleteUsers(ids) {
  return requestWithErrorHandling({
    url: `/users/batch/${ids}`,
    method: "DELETE",
    errorMessage: "批量删除用户失败",
  });
}

// 查询用户状态
export function getUserStatus(id) {
  return requestWithErrorHandling({
    url: `/users/status/${id}`,
    method: "GET",
    errorMessage: "查询用户状态失败",
  });
}

// 修改用户状态
export function updateUserStatus(id, status) {
  return requestWithErrorHandling({
    url: `/users/status/${id}`,
    method: "PUT",
    params: { status },
    errorMessage: "修改用户状态失败",
  });
}

// 获取用户个人数据
export function getUserProfile(id) {
  return requestWithErrorHandling({
    url: `/users/${id}`,
    method: "GET",
    errorMessage: "获取用户信息失败",
  });
}

// 获取用户登录信息（登录状态和设备数）
export function getUserLoginInfo(id) {
  return requestWithErrorHandling({
    url: `/users/login-info/${id}`,
    method: "GET",
    errorMessage: "获取用户登录信息失败",
  });
}

// 强制用户下线
export function forceLogout(id) {
  return requestWithErrorHandling({
    url: `/users/force-logout/${id}`,
    method: "POST",
    errorMessage: "强制下线失败",
  });
}

// 获取所有用户（聊天功能）
export function getAllUsers() {
  return requestWithErrorHandling({
    url: "/users/all",
    method: "GET",
    errorMessage: "获取用户列表失败",
  }).then((res) => {
    if (res.code === 1 && res.data && Array.isArray(res.data.list)) {
      return res.data.list;
    }
    return [];
  });
}

// 发送邮箱验证码
export function sendVerificationCode(email) {
  return requestWithErrorHandling({
    url: "/users/email/send",
    method: "POST",
    params: { email },
    errorMessage: "发送验证码失败",
  });
}
